use crate::resolver::Resolver;
use git2::Repository;
use wang_utils::git::{git_add, git_commit, git_tag};

impl Resolver {
    pub fn commit(&mut self) -> anyhow::Result<()> {
        let args = &self.cli_args;
        if args.skip_commit {
            return Ok(());
        }
        //加载本地git仓库
        let repo = Repository::open(&self.path)?;
        //读取未提交的文件
        let mut options = git2::StatusOptions::new();
        options.include_untracked(true);
        //拿到template中的最新版本号
        let tag_name = self.history.versions[0].name.as_str();
        let tag_str = format!("refs/tags/{tag_name}");
        //根据这个版本号去git库中查询有没有
        let result = repo.revparse_single(tag_str.as_str());
        if let Err(_) = result {
            //如果没有这个tag则新建
            let message = format!("chore(release): {tag_name}");
            //git add
            git_add(&repo)?;
            //git commit
            git_commit(&repo, &message)?;
            //git tag
            git_tag(&repo, &tag_name)?;
        } else {
            println!("git版本中已存在[{tag_name}]版本，请自行提交。");
        }
        Ok(())
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::resolver::cli_args::CliArgs;
    use crate::utils::test_utils::{setup_with_commits_json, teardown_git};

    #[test]
    fn test_commit() -> anyhow::Result<()> {
        let test_folder = setup_with_commits_json("tests/test_commits/test2.json")?;
        let mut args = CliArgs::new();
        args.path = Some(test_folder.to_string());
        let mut resolver = Resolver::init(args)?;
        // 解析git历史
        resolver.resolve()?;
        resolver.handle()?;
        resolver.generate()?;
        resolver.commit()?;
        teardown_git(&test_folder);
        Ok(())
    }
    #[test]
    fn test_commit1() -> anyhow::Result<()> {
        let test_folder = setup_with_commits_json("tests/test_commits/test1.json")?;
        let mut args = CliArgs::new();
        args.path = Some(test_folder.to_string());
        let mut resolver = Resolver::init(args)?;
        // 解析git历史
        resolver.resolve()?;
        resolver.handle()?;
        resolver.generate()?;
        resolver.commit()?;
        // teardown_git(&test_folder);
        Ok(())
    }
}
